﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace BaseLib.Helper
{
    public class Pager
    {
        public Dictionary<int, string> Get(string txtNew, int pageSize)
        {
            var list = new Dictionary<int, string>();
            try
            {
                var tmpStr = string.Empty;
                var count = 0;
                var totalChar = 1;
                var countPage = 1;
                if (!txtNew.IsNullOrWhiteSpace())
                {
                    var mcs = new Regex(@"(.*?<(/table|/p|/div|h\d|hr|br\s*/?)>)", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).Matches(txtNew);//1.匹配可能的段落：(?<Txt>.*?<(/p|br\s*/?)>)
                    if (mcs.Count > 0)
                    {
                        for (var i = 0; i < mcs.Count; i++)
                        {
                            //计算字数
                            var countChar = Regex.Replace(mcs[i].Groups[0].Value, @"<[^>]*>|\s|&nbsp;| |　| ", "", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).Length;
                            if (totalChar + countChar >= pageSize)
                            {
                                tmpStr += mcs[i].Groups[0].Value;
                                list.Add(countPage, tmpStr);//上次的页数和字符串
                                // Next Page：为下一页作准备
                                tmpStr = string.Empty;
                                totalChar = 0;//下页字符数
                                countPage++;//下页页码
                            }
                            else
                            {
                                if (count + 1 == mcs.Count)//处理最后一页。
                                {
                                    var countLast = Regex.Replace(tmpStr + mcs[i].Groups[0].Value, @"<[^>]*>|\s|&nbsp;| |　| ", "", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).Length;
                                    if (countLast < pageSize / 3)//最末段，如果小于 1/4 则附加到上一页
                                        list[countPage - 1] += tmpStr + mcs[i].Groups[0].Value;
                                    else
                                        list.Add(countPage, tmpStr + mcs[i].Groups[0].Value);//处理最后一页。
                                }
                                // Next Page：累积到下一页
                                totalChar += countChar;//累积字符数
                                tmpStr += mcs[i].Groups[0].Value;//累积字符串
                            }
                            count++;
                        }
                    }
                    else
                    {
                        list.Add(countPage, txtNew);
                    }
                }
            }
            catch
            {
            }
            return list;//返回当前页码的文本串
        }
    }
}
